package cake.srcprojector;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;


/**
 * 
 * @author martin.vachon
 */
public class DocTreeWalker {
	private String pageFileName = DocParser.DEFAULT_PAGE_FILE_NAME;
	
	private DocParser docParser = null;
	
	
	public DocTreeWalker(DocParser docParser) {
		this.docParser = docParser;
	}
	
	
	public void start(File folder) throws IOException {
		if (!folder.isDirectory()) {
			return;
		}
		
		File pageFile = new File(folder, pageFileName);
		if (!pageFile.exists()) {
			return;
		}		
		
		DocParserContext docParserContext = new DocParserContext(pageFileName);
		
		docParser.start();
		
		parseFolder(folder, docParserContext);
		
		docParser.end();
	}
	

	private void parseFolder(File folder, DocParserContext docParserContext) throws IOException {
		File page = new File(folder, pageFileName);
		
		
		File[] subFolderArray = folder.listFiles(new FileFilter() {
			@Override
			public boolean accept(File file) {
				return file.isDirectory() && new File(file, pageFileName).exists();
			}
		});
				
		Arrays.sort(subFolderArray);

		docParser.parsePage(page, subFolderArray, docParserContext);
			
		int cnt = 1;
		for (File subFolder : subFolderArray) {
			
			System.out.println(subFolder.getAbsolutePath());
			
			docParser.startFolder(subFolder, docParserContext);
			
			parseFolder(subFolder, docParserContext);
			
			docParser.endFolder(folder, subFolderArray.length == cnt);
			cnt++;
		}
		
	}
	

	public String getPageFileName() {
		return pageFileName;
	}
	public void setPageFileName(String pageFileName) {
		this.pageFileName = pageFileName;
	}
	
}
